import { mongo } from "../mogoConfig";



const run = async () => {
    const zipcodeTB = mongo.db("my_test").collection("zipcodes")

    const cursor1 = zipcodeTB.aggregate([
        { $group: { _id: "$state", totalPop: { $sum: "$pop" } } },
        { $match: { totalPop: { $gte: 1000 * 10000 } } }
    ])

    console.log("聚合结果1-----------------------")
    for await (const item of cursor1) {
        console.log(JSON.stringify(item))
    }

    const cursor2 = zipcodeTB.aggregate([
        {
            $group: {
                _id: { state: "$state", city: "$city" },
                pop: { $sum: "$pop" }
            }
        },
        {
            $group: {
                _id: "$_id.state",
                aveCityPop: { $avg: "$pop" }

            }
        }
    ])

    console.log("聚合结果2-----------------------")
    for await (const item of cursor2) {
        console.log(JSON.stringify(item))
    }


    const cursor3 = zipcodeTB.aggregate([
        {
            $group: {
                _id: { state: "$state", city: "$city" },
                pop: { $sum: "$pop" }
            }
        },
        {
            $sort: { pop: 1 }
        },
        {
            $group: {
                _id: "$_id.state",
                biggestCity: { $last: "$_id.city" },
                biggestPop: { $last: "$pop" },
                smallestCity: { $first: "$_id.city" },
                smallestPop: { $first: "$pop" }

            }
        },
        {
            $project: {
                _id: 0,
                state: "$_id",
                biggest:{
                    name:"$biggestCity",
                    pop:"$biggestPop"
                },
                smallest:{
                    name:"$smallestCity",
                    pop:"$smallestPop"
                }
            }
        }
    ])

    console.log("聚合结果3-----------------------")
    for await (const item of cursor3) {
        console.log(JSON.stringify(item))
    }

}






run()
    .catch(error => {
        console.log(error)
    })
    .finally(() => {
        mongo.close()
        console.log("执行完成")
    })